package com.github.elliot.gatewaycenter.security.service;

import com.github.elliot.domain.PermissionVO;
import com.github.elliot.domain.UserVO;
import com.github.elliot.gatewaycenter.domain.AdminUserPO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.HashSet;


/**
 * @author wwcc
 */
@Slf4j
@Service
public class SecurityUserDetailService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private WebClient.Builder webClientBuilder;

    public Mono<UserDetails> findByUsername(String username) {

        WebClient webClient = WebClient.create();
        String url = "http://127.0.0.1:9001/api/v1/user/username/" + username;

        return webClient.get()
                .uri(url)
                .retrieve()
                .bodyToMono(UserVO.class)
                .map(userVO -> {
                    // 设置用户信息
                    AdminUserPO adminUserPO = new AdminUserPO(username);
                    adminUserPO.setPassword(userVO.getPasswordHash());
                    adminUserPO.setStatus(userVO.getStatus());
                    adminUserPO.setUserNo(userVO.getUserNo());
                    adminUserPO.setBackendUrls(new HashSet<>(userVO.getResourceList()));
                    return adminUserPO;
                });
    }

    public Flux<PermissionVO> findBackendUrlByUserNo(String userNo){
        WebClient webClient = WebClient.create();
        String url = "http://127.0.0.1:9001/api/v1/permissions/by-user-no/" + userNo;

        return webClient.get()
                .uri(url)
                .retrieve()
                .bodyToFlux(PermissionVO.class);
    }
}
